package com.data.structure.day08;

import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Map;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class RSAtest {
	public String privateKey;
	public String publicKey;
	public byte[] data = "哇哈哈".getBytes();

	@Before
	public void init() throws Exception {
		Map<String, Object> keys = RsaUtil.initKey();
		privateKey = RsaUtil.getPrivateKey(keys);
		publicKey = RsaUtil.getPublicKey(keys);
	}

	/**
	 * 私钥加密 公钥解密测试
	 * 
	 * @throws Exception
	 */
	@Test
	public void test1() throws Exception {
		byte[] encryptData = RsaUtil.encryptByPrivateKey(data, privateKey);
		// ? 不一样为什么可以解密成功
		byte[] decryptData = RsaUtil.decryptByPublicKey(encryptData,
				publicKey.substring(0, publicKey.length() - 1));
		Assert.assertArrayEquals(decryptData, data);
	}

	/**
	 * 公钥加密 私钥解密测试
	 * 
	 * @throws Exception
	 */
	@Test
	public void test2() throws Exception {
		byte[] encryptData = RsaUtil.encryptByPublicKey(data, publicKey);
		byte[] decryptData = RsaUtil.decryptByPrivateKey(encryptData,
				privateKey);
		Assert.assertArrayEquals(decryptData, data);
	}

	/**
	 * 使用私钥对信息签名
	 * 
	 * @throws Exception
	 */
	@Test
	public void test3() throws Exception {
		String signData = RsaUtil.sign(data, privateKey);
		Assert.assertTrue(RsaUtil.verify(data, publicKey, signData));
	}

	/**
	 * 通过keystore 获取私钥
	 * 
	 * @throws Exception
	 */
	@Test
	public void test4() throws Exception {

		// 读取keystore文件到KeyStore对象
		FileInputStream in = new FileInputStream("d:/demo.keystore");
		KeyStore ks = KeyStore.getInstance("JKS");// JKS: Java
													// KeyStoreJKS，可以有多种类型
		ks.load(in, "123456".toCharArray());
		in.close();

		// 从keystore中读取证书和私钥
		String alias = "ss"; // 记录的别名
		String pswd = "123456"; // 记录的访问密码
		java.security.cert.Certificate cert = ks.getCertificate(alias);
		PublicKey publicKey = cert.getPublicKey();
		PrivateKey privateKey = (PrivateKey) ks.getKey(alias,
				pswd.toCharArray());
	}

	/**
	 * 生成keystore
	 */
	@Test
	public void genkeyTest() {
		new ExportCertFormKeystore().genkey();
	}

	/**
	 * 生成证书
	 */
	@Test
	public void exportTest() {
		new ExportCertFormKeystore().export();
	}

}
